package com.system.vote.admin.interceptor;

import com.system.vote.admin.exception.CustomJWTException;
import com.system.vote.admin.security.CheckResult;
import com.system.vote.admin.security.JwtUtil;
import com.system.vote.common.Contants;
import com.system.vote.common.utils.StringUtils;
import com.system.vote.core.contant.JWTConstant;
import io.jsonwebtoken.JwtException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserInterceptor implements HandlerInterceptor {
    private static final String[] URL_WHITELIST = {"/app/**"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        String uri = request.getRequestURI();
        Pattern pattern = Pattern.compile("^(" + String.join("|", Contants.URL_APP_WHITELIST) + ")$");
        Matcher matcher = pattern.matcher(uri);
        if (matcher.matches()) {
            return true;
        } else if (StringUtils.checkUrl(URL_WHITELIST, request.getRequestURI())) {
            CheckResult checkResult = JwtUtil.validateJWT(token);
            if (!checkResult.isSuccess()) {
                switch (checkResult.getErrCode()) {
                    case JWTConstant.JWT_ERRCODE_NULL:
                        throw new CustomJWTException("Token不存在");
                    case JWTConstant.JWT_ERRCODE_FAIL:
                        throw new CustomJWTException("Token验证不通过");
                    case JWTConstant.JWT_ERRCODE_EXPIRE:
                        throw new CustomJWTException("Token过期");
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
